package workexp.pom;

import org.apache.commons.lang3.StringUtils;
import org.junit.Test;

import java.io.File;
import java.io.FileFilter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;
import java.util.Scanner;
import java.util.zip.ZipEntry;
import java.util.zip.ZipException;
import java.util.zip.ZipFile;

/**
 * Author:       zhukai
 * Date:         2019/5/20
 * Time:         14:55
 * Mail:         zhukai1@yonyou.com
 * Description:
 * 批量寻找包含某pom的jar包
 */
public class GetPomFromJar {

    @Test
    public void getTargetJar(){
        batchProcessDir("E:\\code\\u8cprint\\WEB-INF\\lib");
    }

    public void batchProcessDir(String dirpath){
        List<String> resultList = new ArrayList<>();
        if(StringUtils.isBlank(dirpath)){
            return;
        }
        File dir = new File(dirpath);
        File[] archives = dir.listFiles(new jarFilter());

        for (int j = 0; j < archives.length; j++) {
            String filename = analyzeJarFile(archives[j]);
            if(StringUtils.isNotBlank(filename)){
                resultList.add(filename);
            }
        }
        resultList.stream().forEach(s->{
            System.out.println(s);
        });

    }

    public String analyzeJarFile(File file){
        String result = file.getName();
        if (!file.exists()) return"";
        try (ZipFile zipFile = new ZipFile(file)){
            Enumeration<? extends ZipEntry> entries = zipFile.entries();
            while (entries.hasMoreElements()){
                ZipEntry entry = entries.nextElement();
                if (entry.getName().endsWith("pom.xml")){
                    try (Scanner scanner = new Scanner(zipFile.getInputStream(entry), "utf-8")){
                        while (scanner.hasNextLine()){
                            String line = scanner.nextLine();
                           // if (line.contains("iris")||line.contains("helix")||line.contains("iuap-bd-translation-api")){
                            if (line.contains("iuap-bd-translation-api")){
                                return result;
                            }
                        }
                    }
                }
            }
        } catch (ZipException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return"";
    }

    static class jarFilter implements FileFilter {
        public boolean accept(File pathName) {
            String upcase = pathName.getName().toUpperCase();
            return upcase.endsWith(".JAR");
        }
    }
}
